package com.liuyjy.encryptDecrypt;

import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author liuyjy
 * @Date 2025/2/20 13:47
 * @Description: 注解元数据处理
 **/
public class CryptoBeanSerializerModifier extends BeanSerializerModifier {
    private final CryptoProvider provider;

    public CryptoBeanSerializerModifier(CryptoProvider provider) {
        this.provider = provider;
    }

    @Override
    public List<BeanPropertyWriter> changeProperties(SerializationConfig config,
                                                     BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
        return beanProperties.stream()
                .map(writer -> {
                    Encrypt encrypt = writer.getAnnotation(Encrypt.class);
                    Decrypt decrypt = writer.getAnnotation(Decrypt.class);

                    if (encrypt != null) {
                        writer.assignSerializer(new DynamicCryptoSerializer(provider, encrypt));
                    }
                    if (decrypt != null) {
                        writer.assignSerializer(new DynamicCryptoSerializer(provider, decrypt));
                    }
                    return writer;
                })
                .collect(Collectors.toList());
    }
}